﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 3/1/2011
 * Time: 8:30 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using TomatoSynchronizer.Entities;
using TomatoSynchronizer.Store;
using HtmlAgilityPack;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace TomatoSynchronizer.Synchronizer
{
	/// <summary>
	/// Description of ArticleSynchronizer
	/// </summary>
	public static class ArticleSynchronizer
	{
		public static void Synchronize(Site siteSrc,Site siteDest,HtmlWeb client,SyncDirection direction)
		{
			switch(direction)
			{
				case SyncDirection.Download:
					UpLoadItems(siteDest,siteSrc,client,direction);
					break;
				case SyncDirection.Upload:
					UpLoadItems(siteSrc,siteDest,client,direction);
					break;
				case SyncDirection.DownloadAndUpload:
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					break;
				case SyncDirection.UploadAndDownload:
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					break;
				case SyncDirection.Synchronize:
					ArticleStore ArticleStoreDest = new ArticleStore(siteDest,client);
					ArticleStoreDest.Truncate();
					
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					break;
			}
		}
		
		private static void UpLoadItems(Site _siteSrc,Site _siteDest,HtmlWeb client,SyncDirection direction)
		{
			ArticleStore ArticleStoreSrc = new ArticleStore(_siteSrc,client);
			ArticleStore ArticleStoreDest = new ArticleStore(_siteDest,client);
			
			Article[] ArticlesSrc =  ArticleStoreSrc.LoadItems();
			Article[] ArticlesDest =  ArticleStoreDest.LoadItems();
			
			MappingStore mappingStoreSrc = new MappingStore(_siteSrc,_siteDest,"articles_id");
			MappingStore mappingStoreDest = new MappingStore(_siteDest,_siteSrc,"articles_id");
			
			mappingStoreSrc.Clean<Article>(ArticleStoreSrc,ArticleStoreDest);
			mappingStoreDest.Clean<Article>(ArticleStoreDest,ArticleStoreSrc);
			
			MappingStore mappingStore = new MappingStore(_siteSrc,_siteDest,"languages_id");
			
			List<Article> alreadySynchronized = new List<Article>();
			
			foreach(Article ArticleSrc in ArticlesSrc)
			{
				//we assume the Article is not yet synchronized
				bool synchronized = false;
				
				//we check if a mapping already exists for this Article in the destination store
				foreach(Mapping mapping in mappingStoreSrc.Mappings)
				{
					if(mapping.SrcValue == ArticleSrc.articles_id && synchronized == false)
					{
						if(!string.IsNullOrEmpty(mapping.DestValue))
						{
							//this Article already exists in the destination store
							//we check if everything changed since the last synchronization
							Article ArticleDest = ArticleStoreDest.GetItem(mapping.DestValue);
							if(!string.IsNullOrEmpty(ArticleDest.articles_id))
							{
								synchronized = SynchronizeItem(ArticleSrc,ArticleDest);
							}
							else
							{
								//the mapping exists, but the Article has been deleted in the destination store
								//we set a flag that this mapping does not exists anymore
								mapping.Exists = false;
							}
						}
					}
				}
				
				if(!synchronized)
				{
					//there is no mapping, we check if this Article already exists in the destination store
					foreach(Article ArticleDest in ArticlesDest)
					{
						foreach(Mapping mapping in mappingStore.Mappings)
						{
							try
							{
								if(ArticleSrc.articles_names["articles_name[" + mapping.SrcValue + "]"] == ArticleDest.articles_names["articles_name[" + mapping.DestValue + "]"] && synchronized == false && !alreadySynchronized.Contains(ArticleSrc))
								{
									//we get the 2 currencies from sites to get sure they really exist
									Article src = ArticleSrc.Store.GetItem(ArticleSrc.articles_id);
									Article dest = ArticleDest.Store.GetItem(ArticleDest.articles_id);
									
									if(!string.IsNullOrEmpty(src.articles_id))
									{
										if(!string.IsNullOrEmpty(dest.articles_id))
										{
											Mapping _mapping = new Mapping(ArticleSrc.articles_id,ArticleDest.articles_id,"articles_id");
											mappingStoreSrc.Mappings.Add(_mapping);
											
											synchronized = SynchronizeItem(ArticleSrc,ArticleDest);
										}
										else
										{
											synchronized = false;
										}
									}
									else
									{
										synchronized = true;
									}
								}
							}
							catch (KeyNotFoundException)
							{
								
							}
						}
						
					}
				}
				
				if(!synchronized)
				{
					//no mapping the Article is new
					//we insert it in the destination store
					string remoteId = string.Empty;										
					
					var languages = ArticleStoreDest.site.GetLanguageStore().LoadItems();
					
					Dictionary<string, string> _articles_descriptions = new Dictionary<string, string>();
					Dictionary<string, string> _articles_names = new Dictionary<string, string>();
					Dictionary<string, string> _articles_urls = new Dictionary<string, string>();
					Dictionary<string, string> _meta_descriptions = new Dictionary<string, string>();
					Dictionary<string, string> _meta_keywordss = new Dictionary<string, string>();
					Dictionary<string, string> _page_titles = new Dictionary<string, string>();
					
					MappingStore _mappingStore = new MappingStore(ArticleSrc.Store.site,ArticleStoreDest.site,"languages_id");
					foreach(Mapping mapping in _mappingStore.Mappings)
					{
						_articles_descriptions["articles_description[" + mapping.DestValue + "]"] = ArticleSrc.articles_descriptions["articles_description[" + mapping.SrcValue + "]"];
						_articles_names["articles_name[" + mapping.DestValue + "]"] = ArticleSrc.articles_names["articles_name[" + mapping.SrcValue + "]"];
						_articles_urls["articles_url[" + mapping.DestValue + "]"] = ArticleSrc.articles_urls["articles_url[" + mapping.SrcValue + "]"];
						_meta_descriptions["meta_description[" + mapping.DestValue + "]"] = ArticleSrc.meta_descriptions["meta_description[" + mapping.SrcValue + "]"];
						_meta_keywordss["meta_keywords[" + mapping.DestValue + "]"] = ArticleSrc.meta_keywordss["meta_keywords[" + mapping.SrcValue + "]"];
						_page_titles["page_title[" + mapping.DestValue + "]"] = ArticleSrc.page_titles["page_title[" + mapping.SrcValue + "]"];
					}

					var old_articles_categories_id  = ArticleSrc.articles_categories_id;
					
					bool exist = false;
					MappingStore categoriesMappingStore = new MappingStore(ArticleSrc.Store.site,ArticleStoreDest.site,"articles_categories_id");
					foreach(Mapping mapping in categoriesMappingStore.Mappings)
					{
						if(mapping.SrcValue == ArticleSrc.articles_categories_id)
						{
							ArticleSrc.articles_categories_id = mapping.DestValue;
							exist = true;
						}
					}
					
					if(!exist)
					{
						throw new Exception("Could not get a mapping for Article Category " + old_articles_categories_id + " from site " + ArticleSrc.Store.site.Name + " to site " + ArticleStoreDest.site.Name);
					}										
					
					ArticleSrc.articles_descriptions = _articles_descriptions;
					ArticleSrc.articles_names = _articles_names;
					ArticleSrc.articles_urls = _articles_urls;
					ArticleSrc.meta_descriptions = _meta_descriptions;
					ArticleSrc.meta_keywordss = _meta_keywordss;
					ArticleSrc.page_titles = _page_titles;
					
					if(!string.IsNullOrEmpty(ArticleSrc.articles_image.ToString()))
					{
						ArticleSrc.articles_image = "sites/" + ArticleSrc.Store.site.Name + "/Articles/originals/" + ArticleSrc.articles_image;
					}					
					
					remoteId = ArticleStoreDest.InsertItem(ArticleSrc);
					
					synchronized = remoteId != string.Empty;
					
					if(!synchronized)
					{
						throw new Exception("The Article " + ArticleSrc.articles_id + " has not been synchronized");
					}
					
					Mapping _mapping = new Mapping(ArticleSrc.articles_id,remoteId,"articles_id");
					mappingStoreSrc.Mappings.Add(_mapping);
					synchronized = true;
				}
				
				if(!synchronized)
				{
					throw new Exception("could not synchronize the Article " + ArticleSrc.articles_id);
				}
				
//				ArticleStoreSrc.PersistItem(ArticleSrc);
				alreadySynchronized.Add(ArticleSrc);
			}
			
			mappingStoreSrc.Save();
			
			mappingStoreDest.Truncate();
			
			//we save the mappings in the destination MappingStore too
			foreach(Mapping mapping in mappingStoreSrc.Mappings)
			{
				if(mapping.Exists)
				{
					Mapping mappingDest = new Mapping(mapping.DestValue,mapping.SrcValue,mapping.Property);
					mappingStoreDest.Mappings.Add(mappingDest);
				}
			}
			
			mappingStoreDest.Save();
			
			//we check if the 2 MappingStore are synchronized
			if(mappingStoreSrc.Mappings.Count != mappingStoreDest.Mappings.Count)
			{
				throw new Exception("The mapping store for the articles are not synchronized");
			}
		}
		
		private static bool SynchronizeItem(Article ArticleSrc,Article ArticleDest)
		{
			bool synchronized = true;
			
			if(!ArticleSrc.Equals(ArticleDest))
			{
				synchronized = false;
				
				//we update the destination Article
				ArticleSrc.language_id = ArticleDest.language_id;
				ArticleSrc.articles_id = ArticleDest.articles_id;
				ArticleSrc.articles_categories_id = ArticleDest.articles_categories_id;
				
				var languages = ArticleDest.Store.site.GetLanguageStore().LoadItems();
				
				Dictionary<string, string> _articles_descriptions = new Dictionary<string, string>();
				Dictionary<string, string> _articles_names = new Dictionary<string, string>();
				Dictionary<string, string> _articles_urls = new Dictionary<string, string>();
				Dictionary<string, string> _meta_descriptions = new Dictionary<string, string>();
				Dictionary<string, string> _meta_keywordss = new Dictionary<string, string>();
				Dictionary<string, string> _page_titles = new Dictionary<string, string>();
				
				MappingStore mappingStore = new MappingStore(ArticleSrc.Store.site,ArticleDest.Store.site,"languages_id");
				foreach(Mapping mapping in mappingStore.Mappings)
				{
					_articles_descriptions["articles_description[" + mapping.DestValue + "]"] = ArticleSrc.articles_descriptions["articles_description[" + mapping.SrcValue + "]"];
					_articles_names["articles_name[" + mapping.DestValue + "]"] = ArticleSrc.articles_names["articles_name[" + mapping.SrcValue + "]"];
					_articles_urls["articles_url[" + mapping.DestValue + "]"] = ArticleSrc.articles_urls["articles_url[" + mapping.SrcValue + "]"];
					_meta_descriptions["meta_description[" + mapping.DestValue + "]"] = ArticleSrc.meta_descriptions["meta_description[" + mapping.SrcValue + "]"];
					_meta_keywordss["meta_keywords[" + mapping.DestValue + "]"] = ArticleSrc.meta_keywordss["meta_keywords[" + mapping.SrcValue + "]"];
					_page_titles["page_title[" + mapping.DestValue + "]"] = ArticleSrc.page_titles["page_title[" + mapping.SrcValue + "]"];
				}
				
				ArticleSrc.articles_descriptions = _articles_descriptions;
				ArticleSrc.articles_names = _articles_names;
				ArticleSrc.articles_urls = _articles_urls;
				ArticleSrc.meta_descriptions = _meta_descriptions;
				ArticleSrc.meta_keywordss = _meta_keywordss;
				ArticleSrc.page_titles = _page_titles;
				
				synchronized = ArticleDest.Store.UpdateItem(ArticleSrc);
			}
			
			return synchronized;
		}
		
		private static string UploadItem(ArticleStore ArticleStoreDest,Article Article)
		{
			string remoteId = string.Empty;
			
			remoteId = ArticleStoreDest.InsertItem(Article);
			
			return remoteId;
		}
	}
}
